const { privateKey, publicKey } = require("../config/keys");
const jwt = require("jsonwebtoken");
const { UNAUTHORIZATION } = require("../constant/index");

class LoginController {
  //登录逻辑
  login(ctx, next) {
    const { name, id } = ctx.user;
    const payload = { id, name };
    //颁发token
    const token = jwt.sign(payload, privateKey, {
      expiresIn: 60 * 60 * 24 * 30,
      algorithm: "RS256",
    });

    ctx.body = { data: { id, name, token }, code: 200, message: "用户登录成功" };
  }

  //登录测试
  loginTest(ctx, next) {
    try {
      //获取客户端携带过来的token
      const authorization = ctx.headers.authorization;
      const token = authorization.replace(`Bearer `, "");

      //验证token
      const result = jwt.verify(token, publicKey, { algorithms: ["RS256"] });
      ctx.body = { code: 200, message: "token验证成功" };
    } catch (error) {
      console.log(error, "error login middleware");
      ctx.app.emit("error", UNAUTHORIZATION, ctx);
    }
  }
}

module.exports = new LoginController();
